package xyz.jcat.biz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import xyz.jcat.biz.admin.domain.dao.IPermissionDao;
import xyz.jcat.biz.admin.domain.po.PermissionPo;
import xyz.jcat.biz.admin.service.IPermissionService;
import xyz.jcat.mybatis.ServiceImpl;
import xyz.jcat.web.security.PermissionType;
import xyz.jcat.web.security.PermissionUtils;

import java.util.List;
import java.util.Objects;

/**
 *
 * @author yueyue
 * auto on 2022-04-28 13:41:47
 */
@Service
public class PermissionService extends ServiceImpl<IPermissionDao, PermissionPo> implements IPermissionService {

    private static final String CONTROLLER_PACKAGE = "xyz.jcat.biz.admin.web.controller";
    @Override
    public PermissionPo getByPermission(String permission) {
        LambdaQueryWrapper<PermissionPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PermissionPo::getPermission, permission);
        return getOne(lambdaQueryWrapper);
    }

    @Override
    public void refresh() {
        List<PermissionUtils.MenuPermission> menuPermissions = PermissionUtils.getMenuPermissions(CONTROLLER_PACKAGE);
        for (PermissionUtils.MenuPermission menuPermission : menuPermissions) {
            PermissionPo menu;
            PermissionPo oldMenu = getByPermission(menuPermission.getPermission());
            if(Objects.isNull(oldMenu)) {
                menu = new PermissionPo();
                menu.setPermissionType(PermissionType.MENU.name());
                menu.setPermissionName(menuPermission.getName());
                menu.setPermission(menuPermission.getPermission());
                insert(menu);
            }else {
                menu = oldMenu;
            }
            for (PermissionUtils.ButtonPermission buttonPermission : menuPermission.getButtons()) {
                PermissionPo oldButton = getByPermission(buttonPermission.getPermission());
                if(Objects.isNull(oldButton)) {
                    PermissionPo button = new PermissionPo();
                    button.setPermissionType(PermissionType.BUTTON.name());
                    button.setPermissionName(buttonPermission.getName());
                    button.setPermission(buttonPermission.getPermission());
                    button.setReqMethod(buttonPermission.getReqMethod());
                    button.setReqUri(buttonPermission.getReqUri());
                    button.setPid(menu.getId());
                    insert(button);
                }
            }
        }
    }
}
